package com.funny.factory;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author Ming
 * @description 自定义路由断言工厂,需要以 RoutePredicateFactory 为后缀
 * @fileSimpleName CheckAuthRoutePredicateFactory
 * @fileName com.funny.factory.CheckAuthRoutePredicateFactory
 * @date 2024年06月28日 15:49
 */
@Slf4j
@Component
public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> {

    public CheckAuthRoutePredicateFactory() {
        super(CheckAuthRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name");
    }

    @Override
    public Predicate<ServerWebExchange> apply(CheckAuthRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                if (config.getName().equals("MING")){
                    return true;
                }
                return false;
            }

            @Override
            public Object getConfig() {
                return config;
            }

        };
    }

    // 用于接收配置文件中 断言的信息
    @Data
    @Validated
    public static class Config {

        @NotEmpty
        private String name;

    }


}
